import React, { Component } from 'react';
import { Button, Card, Modal, Form, Input, message, Table } from "antd"
import { RoleAdd, RoleGet, RoleUpdate } from "../../../api/index"
import PermissionTree from "./PermissionTree"
import storageUtils from "../../../utils/storageUtils"

class role extends Component {
    constructor(props) {
        super(props);
        this.tree = React.createRef() //获取到PermissionTree组件的标记
    }
    state = {
        loading: true,
        resetVisible: false,
        visible: false,
        roleList: [],
        selectedRowKeys: [], // Check here to configure the default column
        role: {},
    }

    componentDidMount() {
        this.getRole();
    }

    // 添加角色窗口添加取消按钮触发的事件
    handlerCanel = () => {
        this.setState({
            resetVisible: false
        })
        this.form.props.form.resetFields()
    }

    // 添加角色窗口添加确认按钮触发的事件
    handlerOk = () => {
        this.form.props.form.validateFields(async (err, values) => {
            const result = await RoleAdd(values);
            const { status, msg } = result;
            if (status) {
                message.success(msg)
                this.setState({
                    resetVisible: false
                })
                this.form.props.form.resetFields()
                this.getRole();
            } else {
                message.error(msg)
            }
        })


    }

    // 点击添加角色按钮触发的事件
    handlerRole = () => {
        this.setState({
            resetVisible: true
        })
    }


    // 点击权限窗口取消按钮触发的事件
    clickCanel = () => {
        this.setState({
            visible: false
        })
    }

    // 点击权限窗口按钮触发的事件
    clickOk = () => {
        const { role } = this.state;
        role.menus = this.tree.current.state.checkedKeys;
        role.authorCreateTime = new Date();
        role.authorName = storageUtils.getUser().userName
        this.updateRole(role) 
    }

    updateRole = async (Role) => {
        const result = await RoleUpdate(Role)
        const {status,msg} =result;
        if(status){
            message.success(msg)
            this.setState({
                visible: false
            })
        }else{
            message.error(msg)
        }
    }

    // 点击添加角色按钮触发的事件
    onshow = () => {
        this.setState({
            visible: true
        })
    }



    // 获取角色
    getRole = async () => {
        const roleList = await RoleGet();
        this.setState({
            roleList,
            loading: false
        })
    }



    render() {

        const { roleList, loading, selectedRowKeys, role } = this.state;

        const title = (
            <span>
                <Button type="primary" icon="plus" onClick={this.handlerRole}>添加角色</Button>
                <Button type="primary" style={{ marginLeft: 20 }} disabled={!role._id} onClick={this.onshow}>设置角色权限</Button>
            </span>
        )


        const columns = [
            {
                title: '角色名称',
                dataIndex: 'roleName',
                key: 'roleName',
            },
            {
                title: '创建时间',
                dataIndex: 'roleCreateTime',
                key: 'roleCreateTime',
                render: (roleCreateTime) => (
                    <span>{new Date(roleCreateTime).toLocaleString()}</span>
                )
            },
            {
                title: '授权人',
                dataIndex: 'authorName',
                key: 'authorName',
            },
            {
                title: '授权时间',
                dataIndex: 'authorCreateTime',
                key: 'authorCreateTime',
                render: (authorCreateTime) => {
                   
                    if(authorCreateTime){
                       return <span>{new Date(authorCreateTime).toLocaleString()}</span>
                    }
                   
                    
                }
            }
        ];

        return (
            <div>
                <Card title={title} style={{ borderBottom: "none" }}>
                    <Table
                        dataSource={roleList}  //数据源
                        columns={columns} //每列的信息
                        rowKey="_id"
                        bordered
                        rowSelection={{
                            type: "radio",  //决定是单选还是多选的选项
                            selectedRowKeys,
                            // onChange:selectedRowKeys => {
                            //     // console.log(selectedRowKeys)  //selectedRowKeys 是所选项的_id值
                            //     this.setState({ selectedRowKeys });
                            // }
                        }}
                        //设置行属性 ，role是当前点击的行的role对象
                        onRow={role => {
                            return {
                                onClick: event => {
                                    this.setState({
                                        selectedRowKeys: [role._id],
                                        role
                                    });
                                }, // 点击行
                            };
                        }}
                        loading={loading}
                        pagination={{ defaultPageSize: 4 }}

                    />

                    <Modal
                        title="添加角色"
                        visible={this.state.resetVisible}
                        onOk={this.handlerOk}
                        onCancel={this.handlerCanel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <NewAddRole wrappedComponentRef={(form) => this.form = form}></NewAddRole>
                    </Modal>
                    <Modal
                        title="设置角色权限"
                        visible={this.state.visible}
                        onOk={this.clickOk}
                        onCancel={this.clickCanel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <PermissionTree ref={this.tree} role={role}></PermissionTree>
                    </Modal>
                </Card>
            </div>
        );
    }
}



class AddRole extends Component {
    render() {
        const { getFieldDecorator } = this.props.form
        return (
            <div>
                <Form>
                    <Form.Item>
                        {
                            getFieldDecorator("roleName", {
                                rules: [
                                    { required: true, message: '角色名不能为空' }
                                ]
                            })(
                                <Input placeholder="请输入角色名"></Input>
                            )
                        }
                    </Form.Item>
                </Form>
            </div>
        )
    }
}

const NewAddRole = Form.create()(AddRole)


export default role;